﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClassLib.Classes.Common;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraSplashScreen;
using ISumen;
using Sumen.Business;
using Sumen.Business.Model;
using Sumen.Business.Model.Presenter.Actor;
using Sumen.Business.Model.Presenter.Category;
using Sumen.Business.Model.Presenter.Inventory;
using Sumen.Business.Model.Presenter.Sales;
using Sumen.Business.Model.Presenter.Sys;
using Sumen_Stock.LookAndFeel.Sales;
using Sumen_Stock.LookAndFeel.Sumen_System;

namespace Sumen_Stock.LookAndFeel.Admin
{
    public partial class Frm_Manager_Orders : DevExpress.XtraEditors.XtraForm
    {

        #region Variable

        private OrdersPresenter _ordersPresenter;
        private CustomerPresenter _customerPresenter;
        private CustomerTypePresenter _customerTypePresenter;
        private ProductDetailsPresenter _productDetailPresenter;
        private ProductPresenter _productPresenter;
        private OrderStatusPresenter _orderStatusPresenter;
        private InventoryPresenter _inventoryPresenter;
        private EmployeePresenter _employeePresenter;
        private bool isChange = false;
        private bool isOutOfStock = false;

        #endregion

        #region Variable order details
        private string _productDetailsId;
        private ICollection<order> _ordersList;
        //private List<orders_details> _ordersDetailses;
        private order _order;
        private customer _cus;
        string urlDesImageOrders = ClassLib.Classes.Connection.ClsConnection.LocationSave;
        #endregion

        #region From

        public Frm_Manager_Orders()
        {
            InitializeComponent();
            _ordersPresenter = new OrdersPresenter();
            _customerPresenter = new CustomerPresenter();
            _customerTypePresenter = new CustomerTypePresenter();
            _productDetailPresenter = new ProductDetailsPresenter();
            _productPresenter = new ProductPresenter();
            _orderStatusPresenter = new OrderStatusPresenter();
            _inventoryPresenter = new InventoryPresenter();
            _employeePresenter = new EmployeePresenter();
            txtSearchDate.EditValue = DateTime.Today;

            urlDesImageOrders = Path.Combine(urlDesImageOrders, "HoaDon");

        }

        public override void Refresh()
        {
            SplashScreenManager.ShowForm(typeof(WaitForm1));
            base.Refresh();
            LoadForm();
            SplashScreenManager.CloseForm();
        }

        private void Frm_Manager_Orders_Load(object sender, EventArgs e)
        {
            LoadForm();
        }

        private void Frm_Manager_Orders_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isChange)
            {
                if (!ClsMsgBox.XacNhanDongTab())
                {
                    e.Cancel = true;
                    return;
                }
                this.Dispose();
            }
        }


        #endregion


        #region button

        private void buttonsArray1_btnEventUpdate_click(object sender, EventArgs e)
        {
            if (Validation())
            {
                //pOrder.Ord_Code = txtCodeSales.EditValue + string.Empty;
                _order.Ord_Customer_ID = (string)lookUpOrderCus.EditValue;
                _order.Ord_Customer_Name = txtOrderCusName.EditValue + string.Empty;
                _order.Ord_Customer_Contact = txtOrderCusPhone.EditValue + string.Empty;
                _order.Ord_Date_Orders = DateTime.Now;
                _order.Ord_DiscountRate = Convert.ToInt32(spinDiscount.Value);
                _order.Ord_VAT = 0;
                _order.Ord_Total_Amount = Convert.ToDecimal(txtSummary.EditValue);
                _order.Ord_Discount = 0;
                _order.Ord_Cash = Convert.ToDecimal(txtCash.EditValue);
                _order.Ord_Change = Convert.ToDecimal(txtCharge.EditValue);
                _order.Ord_Deposit = Convert.ToDecimal(txtDeposit.EditValue);
                _order.Ord_Payment_Status = (int?)(lookUpOrdersStatus.EditValue);
                _order.Ord_User_ID = ClsPublic.User.User_Username;
                _order.Ord_Description = txtOrdersDesc.EditValue + string.Empty;

                SplashScreenManager.ShowForm(typeof(WaitForm1));
                Frm_Confirm_Sales obj = new Frm_Confirm_Sales( _order, _cus);
                SplashScreenManager.CloseForm();
                obj.FormStatus = EnumFormStatus.Modify;
                obj.ShowDialog();
                if (obj.IsSales)
                {
                    if ((int)lookUpOrdersStatus.EditValue == (int)OrdersStatus.Paid)
                    {
                        lookUpOrdersStatus.Properties.ReadOnly = true;
                        lookUpOrderCus.Properties.ReadOnly = true;
                        btnAdd.Enabled = false;
                        buttonsArray1.btnSua.Enabled = false;
                        buttonsArray1.btnXoa.Enabled = false;
                    }
                    LoadOrdersList();
                }



            }
        }

        private void buttonsArray1_btnEventDelete_click(object sender, EventArgs e)
        {
            //xac nhan xóa hóa đơn ngoại trừ hóa đơn đã thanh toán ra
            if (_order != null && _order.Ord_Payment_Status != (int)OrdersStatus.Paid && ClsMsgBox.XacNhan("Bạn có chắc xóa hóa đơn " + _order.Ord_Code + "?\nCác dữ liệu đã bị xóa sẽ không thể phục hồi được nữa.\nBạn có chắc muốn xóa dữ liệu này?"))
            {
                //xoa hóa đơn ở đây
                if (_ordersPresenter.Delete(_order.orders_details.ToList(), _order) > 0)
                {
                    ClsMsgBox.ThongTin("Xóa hóa đơn thành công.");
                    ClsPublic.WriteLog(_fromCode, EnumFormStatus.Delete, _order.Ord_Code, "");
                    ResetForm();
                }
            }
        }

        private void buttonsArray1_btnEventClose_click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonsArray1_btnEventPrint_click(object sender, EventArgs e)
        {
            SplashScreenManager.ShowForm(typeof(WaitForm1));
            Frm_Confirm_Sales obj = new Frm_Confirm_Sales( _order, _cus);
            SplashScreenManager.CloseForm();
            obj.FormStatus = EnumFormStatus.Print;
            obj.ShowDialog();
        }

        #endregion

        /// ######################################################################################

        #region Event Control Order detail

        private void txtDeposit_EditValueChanged(object sender, EventArgs e)
        {
            _order.Ord_Deposit = Convert.ToInt32(txtDeposit.EditValue);
            SetCharge();
        }

        private void txtCash_EditValueChanged(object sender, EventArgs e)
        {
            _order.Ord_Cash = Convert.ToInt32(txtCash.EditValue);
            SetCharge();
        }

        private void txtSummary_EditValueChanged(object sender, EventArgs e)
        {
            SetCharge();
        }

        private void spinDiscount_EditValueChanged(object sender, EventArgs e)
        {
            if (_order != null)
            {
                _order.Ord_DiscountRate = Convert.ToInt32(spinDiscount.EditValue);
                SetCharge();
            }
        }



        #endregion


        #region Method orders details

        void SetCharge()
        {
            if (_order != null)
            {
                txtSummary.EditValue = _order.Ord_Total_Amount;
                if (!string.IsNullOrEmpty(lookUpOrdersStatus.EditValue + string.Empty) && (int)lookUpOrdersStatus.EditValue == (int)OrdersStatus.Paid)
                {

                    txtCharge.EditValue = _order.Ord_Change;
                }
                else
                {
                    txtCharge.EditValue = 0;
                    txtCash.EditValue = 0;
                }

                gvOrderDetails.RefreshData();
                if (gvOrderDetails.UpdateCurrentRow())
                {
                    gvOrderDetails.UpdateTotalSummary();
                }
            }
        }

        #endregion


        #region Event Gridview Order details

        private void gcOrderDetails_KeyDown(object sender, KeyEventArgs e)
        {
            int row = gvOrderDetails.FocusedRowHandle;
            if ((e.KeyCode == Keys.Delete))
            {
                if (_order != null)
                {
                    if (ClsMsgBox.XacNhanXoaThongTin())
                    {
                        string productDetailsId = gvOrderDetails.GetFocusedRowCellValue(colProductDetailsID) + string.Empty;
                        gvOrderDetails.DeleteRow(row);
                        //_order.orders_details.Remove(_order.orders_details.FirstOrDefault(p => p.Ords_PRODUCT_DETAILS_ID == productDetailsId));
                        //var result = new BindingSource(_order.orders_details, "");
                        // gcOrderDetails.DataSource = result;
                        //check san pham co fai la hàng hết không--> enable lookup status
                        var query = from p in _order.orders_details
                                    where p.Ords_Quantity > Convert.ToInt32(p.Ords_Temp)
                                    select p;
                        if (query.Any())
                        {
                            isOutOfStock = true;
                        }
                        else
                        {
                            isOutOfStock = false;
                        }
                        SetCharge();
                        isChange = true;
                    }
                }


            }
        }

        private void gvOrderDetails_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            isChange = true;
            // SetSummaryText();
            SetCharge();
            if (gvOrderDetails.UpdateCurrentRow())
            {
                gvOrderDetails.UpdateTotalSummary();
            }
        }

        private void gvOrderDetails_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void gvOrderDetails_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            int iRow = gvOrderDetails.FocusedRowHandle;


            string sDiscount = gvOrderDetails.GetRowCellValue(iRow, colDiscount) + string.Empty;
            string sQuantity = gvOrderDetails.GetRowCellValue(iRow, colQuantity) + string.Empty;
            string sPrice = gvOrderDetails.GetRowCellValue(iRow, colPriceUnit) + string.Empty;

            ////////////////////////////////////////////////////////////////////////////
            if (string.IsNullOrEmpty(sPrice) || sPrice == "0")
            {
                gvOrderDetails.SetColumnError(colPriceUnit, string.Format("Bạn chưa nhập giá sản phẩm! ESC để bỏ qua."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            if (string.IsNullOrEmpty(sQuantity) || sQuantity == "0")
            {
                gvOrderDetails.SetColumnError(colQuantity, string.Format("Bạn chưa nhập số lượng sản phẩm! ESC để bỏ qua."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            if (string.IsNullOrEmpty(sDiscount))
            {
                gvOrderDetails.SetColumnError(colDiscount, string.Format("Bạn chưa nhập giảm giá! ESC để bỏ qua."));
                e.Valid = false;
            }
        }

        private void gvOrderDetails_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (!string.IsNullOrEmpty(lookUpOrdersStatus.EditValue + string.Empty) && (int)lookUpOrdersStatus.EditValue != (int)OrdersStatus.Paid)
            {
                GridView View = sender as GridView;
                if (e.RowHandle >= 0)
                {
                    int quantityStock = Convert.ToInt32(View.GetRowCellDisplayText(e.RowHandle, colOutOfStock));
                    int quanitity = Convert.ToInt32(View.GetRowCellDisplayText(e.RowHandle, colQuantity));
                    if (quantityStock < quanitity)
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
                    }
                    else
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Regular);
                    }
                    //check san pham co fai la hàng hết không--> enable lookup status
                    var query = from p in _order.orders_details
                                where p.Ords_Quantity > Convert.ToInt32(p.Ords_Temp)
                                select p;
                    if (query.Any())
                    {
                        isOutOfStock = true;
                    }
                    else
                    {
                        isOutOfStock = false;
                    }
                }
            }
        }

        private void gvOrderDetails_DoubleClick(object sender, EventArgs e)
        {
            //if (gvOrderDetails.FocusedColumn == colPictureOrders)
            //{
            //    string imageName = gvOrderDetails.GetFocusedRowCellValue(colImageOrders)+string.Empty;
            //    string productDetailsId = gvOrderDetails.GetFocusedRowCellValue(colProductDetailsID) + string.Empty;
            //}
        }

        #endregion

        /// ######################################################################################

        #region Event Control Order

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadOrdersList();
        }

        private void btnSearchOrder_Click(object sender, EventArgs e)
        {

        }

        private void btnSearchCancel_Click(object sender, EventArgs e)
        {

        }

        private void lookUpOrderCus_searchLookUpEdit_EditValueChanged(object sender, EventArgs e)
        {
            customer cus = _customerPresenter.GetById(lookUpOrderCus.EditValue);
            if (cus != null)
            {
                lookUpOrderCusType.EditValue = cus.Cus_CUSTOMER_TYPE_ID;
                txtOrderCusName.EditValue = cus.Cus_FullName;
                txtOrderCusPhone.EditValue = cus.Cus_Phone;
                txtOrderCusAddress.EditValue = cus.Cus_Address;
            }
            else
            {
                lookUpOrderCusType.EditValue = null;
                txtOrderCusName.EditValue = null;
                txtOrderCusPhone.EditValue = null;
                txtOrderCusAddress.EditValue = null;
            }

        }

        private void lookUpOrdersStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(lookUpOrdersStatus.EditValue + string.Empty) && (int)lookUpOrdersStatus.EditValue == (int)OrdersStatus.Paid)
            {
                txtCash.Properties.ReadOnly = false;
            }
            else
            {
                txtCash.Properties.ReadOnly = true;
                txtCash.EditValue = 0;
            }
            _order.Ord_Payment_Status = (int)lookUpOrdersStatus.EditValue;
        }

        #endregion


        #region Event Gridview Order

        private void gvOrdersList_DoubleClick(object sender, EventArgs e)
        {
            if (_ordersList != null && _ordersList.Count > 0)
            {
                long ordersId = Convert.ToInt64(gvOrdersList.GetRowCellDisplayText(gvOrdersList.FocusedRowHandle, colOrderId));
                _order = _ordersPresenter.GetById(ordersId);
               // _ordersDetailses = _order.orders_details.ToList();
                foreach (var ordersDetailse in _order.orders_details)
                {
                    int quantityStock = _inventoryPresenter.GetByProductDetailsId(ordersDetailse.Ords_PRODUCT_DETAILS_ID).Sum(p => p.Inv_Quantity) ?? 0;
                    ordersDetailse.Ords_Temp = quantityStock + string.Empty;
                    ordersDetailse.Ords_Picture = _productPresenter.GetPicture(urlDesImageOrders, _order.Ord_Code,
                        ordersDetailse.Ords_IsOrders_Image);
                }

                //_order = _ordersList.FirstOrDefault(o => o.Ord_ID == ordersId);
                var query = new BindingSource(_order.orders_details, "");
                gcOrderDetails.DataSource = query;

                if (_order.Ord_IsOrder == 1)
                {
                    colPictureOrders.VisibleIndex = 8;
                    gvOrderDetails.RowHeight = 50;
                }
                else
                {
                    colPictureOrders.VisibleIndex = -1;
                    gvOrderDetails.RowHeight = -1;
                }
                gvOrderDetails.BestFitColumns();
                //load thong tin order o day
                txtOrderCode.EditValue = _order.Ord_Code;
                lookUpOrdersStatus.EditValue = _order.Ord_Payment_Status;
                txtOrderDate.EditValue = _order.Ord_Date_Orders;
                employee emp = _employeePresenter.GetById(_order.Ord_User_ID);
                txtOrderUser.EditValue = emp.Emp_FullName;
                txtOrdersDesc.EditValue = _order.Ord_Description;
                //load thong tin khach hang o day
                lookUpOrderCus.EditValue = _order.Ord_Customer_ID;
                _cus = _customerPresenter.GetById(_order.Ord_Customer_ID);
                lookUpOrderCusType.EditValue = _cus.Cus_CUSTOMER_TYPE_ID;
                txtOrderCusName.EditValue = _order.Ord_Customer_Name;
                txtOrderCusPhone.EditValue = _order.Ord_Customer_Contact;
                txtOrderCusAddress.EditValue = _order.Ord_Customer_Address;
                //load thong in tien cua hoa don
                txtDeposit.EditValue = _order.Ord_Deposit;
                spinDiscount.EditValue = _order.Ord_DiscountRate;

                SetCharge();
                if (_order.Ord_Payment_Status == (int)OrdersStatus.Paid)
                {
                    lookUpOrdersStatus.Properties.ReadOnly = true;
                    lookUpOrderCus.Properties.ReadOnly = true;
                    btnAdd.Enabled = false;
                    buttonsArray1.btnSua.Enabled = false;
                    buttonsArray1.btnXoa.Enabled = false;
                    txtCash.Properties.ReadOnly = true;
                    txtDeposit.Properties.ReadOnly = true;
                    txtCash.EditValue = _order.Ord_Cash;
                    spinDiscount.Properties.ReadOnly = true;
                }
                else
                {
                    lookUpOrdersStatus.Properties.ReadOnly = false;
                    lookUpOrderCus.Properties.ReadOnly = false;
                    btnAdd.Enabled = true;
                    buttonsArray1.btnSua.Enabled = true;
                    buttonsArray1.btnXoa.Enabled = true;
                    txtCash.Properties.ReadOnly = false;
                    spinDiscount.Properties.ReadOnly = false;
                    txtDeposit.Properties.ReadOnly = false;

                }
            }
        }

        private void gvOrdersList_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView View = sender as GridView;
            if (e.RowHandle >= 0)
            {
                int orderStatus = Convert.ToInt32(View.GetRowCellValue(e.RowHandle, colOrderStatus));
                if (orderStatus == (int)OrdersStatus.Paid)
                {
                    e.Appearance.ForeColor = Color.DarkGreen;
                }
                else
                {
                    e.Appearance.ForeColor = Color.Red;
                }

            }
        }

        #endregion


        /// ######################################################################################


        #region Event Control Add product

        private Frm_Search_Product _frmSearchProduct;
        private void txtProductDetailsId_EditValueChanged(object sender, EventArgs e)
        {
            if (_productDetailPresenter.CheckValidCodeProductDetails(txtProductDetailsId.EditValue + string.Empty))
            {
                _productDetailsId = txtProductDetailsId.EditValue + string.Empty;
                LoadProduct(txtProductDetailsId.EditValue + string.Empty);
                txtProductDetailsId.EditValue = null;
                txtProductDetailsId.Properties.NullText = _productDetailsId;
                //txtProductDetailsId.MaskBox.EditValue = null;
                txtProductDetailsId.Focus();
            }
        }

        void Frm_Search_Product_gridView1_DoubleClick(object sender, EventArgs e)
        {
            txtProductDetailsId.EditValue = _frmSearchProduct.gridView1.GetRowCellDisplayText(_frmSearchProduct.gridView1.FocusedRowHandle, _frmSearchProduct.colProductID);
            _frmSearchProduct.Close();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            _frmSearchProduct = new Frm_Search_Product();
            _frmSearchProduct.gridView1.DoubleClick += Frm_Search_Product_gridView1_DoubleClick;
            _frmSearchProduct.ShowDialog();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (_productDetailPresenter.CheckValidCodeProductDetails(_productDetailsId + string.Empty))
            {
                AutoAddProductDetails();
            }
        }

        #endregion


        #region Method add product

        private void AutoAddProductDetails()
        {
            if (_order != null && _order.Ord_Payment_Status != (int)OrdersStatus.Paid)
            {
                orders_details ordersDetails = _order.orders_details.FirstOrDefault(p => p.Ords_PRODUCT_DETAILS_ID == _productDetailsId + string.Empty);
                //add
                if (ordersDetails == null)
                {
                    ordersDetails = new orders_details();
                    ordersDetails.Ords_PRODUCT_DETAILS_ID = _productDetailsId + string.Empty;
                    ordersDetails.Ords_Product_Name = txtProductName.EditValue.ToString();
                    ordersDetails.Ords_Discount = (decimal?)(txtDiscount.EditValue) ?? 0;
                    ordersDetails.Ords_Quantity = Convert.ToInt32(txtQuantity.EditValue);
                    ordersDetails.Ords_Temp = _inventoryPresenter.GetQuantityByProductDetailsId(_productDetailsId + string.Empty).ToString();
                    if (_cus == null)
                    {
                        ordersDetails.Ords_UnitPrice = Convert.ToDecimal(txtSalePrice.EditValue);
                        ordersDetails.Ords_Amount = ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity;
                    }
                    else if (_cus.customer_type.CusT_PriceTypeId == (int)PriceType.SalePrice)
                    {
                        ordersDetails.Ords_UnitPrice = Convert.ToDecimal(txtSalePrice.EditValue);
                        ordersDetails.Ords_Amount = ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity;
                    }
                    else if (_cus.customer_type.CusT_PriceTypeId == (int)PriceType.RetailsPrice)
                    {
                        ordersDetails.Ords_UnitPrice = Convert.ToDecimal(txtRetailPrice.EditValue);
                        ordersDetails.Ords_Amount = ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity;
                    }
                    else if (_cus.customer_type.CusT_PriceTypeId == (int)PriceType.AgentPrice)
                    {
                        ordersDetails.Ords_UnitPrice = Convert.ToDecimal(txtAgentPrice.EditValue);
                        ordersDetails.Ords_Amount = ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity;
                    }
                    _order.orders_details.Add(ordersDetails);
                    gvOrderDetails.RefreshData();
                    SetCharge();
                }
                //plus quantity
                else
                {
                    ordersDetails.Ords_Quantity++;
                    ordersDetails.Ords_Amount = (ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity) -
                                                ordersDetails.Ords_Discount;
                    gvOrderDetails.RefreshData();
                    SetCharge();
                }
                gvOrderDetails.FocusedRowHandle = _order.orders_details.Count - 1;
                if (ordersDetails.Ords_Quantity > Convert.ToInt32(txtQuantityStock.EditValue))
                {
                    isOutOfStock = true;
                }
            }

        }

        private void LoadProduct(string pProductDetailId)
        {
            var invent = _inventoryPresenter.GetByProductDetailsId(pProductDetailId);
            if (invent.Count != 0)
            {
                _productDetailsId = invent.First().product_details.Prods_ID;
                txtProductName.EditValue = invent.First().product_details.product.Prod_Product_Name;
                txtColor.EditValue = invent.First().product_details.product_color.Color_Name;
                txtSize.EditValue = invent.First().product_details.product_size.Size_Name;
                txtSalePrice.EditValue = invent.First().Inv_Sale_Price;
                txtAgentPrice.EditValue = invent.First().Inv_Agent_Price;
                txtRetailPrice.EditValue = invent.First().Inv_Retails_Price;
                txtDiscount.EditValue = invent.First().product_details.product.Prod_Discount ?? 0;
                txtQuantity.EditValue = 1;
                txtQuantityStock.EditValue = invent.Sum(p => p.Inv_Quantity);
                picProduct.EditValue =
                    _productPresenter.GetPicture(_productPresenter.UrlDesImage, invent.First().product_details.product.Prod_Product_ID, invent.First().product_details.product.Prod_Image);
                if (chkAutoAdd.Checked)
                {
                    AutoAddProductDetails();
                }
            }
            else
            {
                var productDetails = _productDetailPresenter.GetById(pProductDetailId);
                if (productDetails != null)
                {
                    _productDetailsId = productDetails.Prods_ID;
                    txtProductName.EditValue = productDetails.product.Prod_Product_Name;
                    txtColor.EditValue = productDetails.product_color.Color_Name;
                    txtSize.EditValue = productDetails.product_size.Size_Name;
                    txtSalePrice.EditValue = productDetails.product.Prod_Sale_Price;
                    txtAgentPrice.EditValue = productDetails.product.Prod_Agent_Price;
                    txtRetailPrice.EditValue = productDetails.product.Prod_Retails_Price;
                    txtDiscount.EditValue = productDetails.product.Prod_Discount ?? 0;
                    txtQuantity.EditValue = 1;
                    txtQuantityStock.EditValue = 0;
                    picProduct.EditValue =
                    _productPresenter.GetPicture(_productPresenter.UrlDesImage, productDetails.product.Prod_Product_ID, productDetails.product.Prod_Image);
                    if (chkAutoAdd.Checked)
                    {
                        AutoAddProductDetails();
                    }
                }
            }
        }

        #endregion


        /// ######################################################################################


        #region Method Load Form

        void LoadForm()
        {
            LoadCustomer();
            LoadOrdersStatus();
            LoadOrdersList();
        }

        void LoadCustomer()
        {
            LoadCustomerType();
            lookUpOrderCus.DataSource = lookUpSearchCus.DataSource = _customerPresenter.GetByKey(1);
        }

        void LoadCustomerType()
        {
            lookUpOrderCusType.Properties.DataSource = lookUpSearchCus.DataSourceCustomerType = lookUpOrderCus.DataSourceCustomerType = _customerTypePresenter.GetAll();
        }

        void LoadOrdersStatus()
        {
            lookUpOrdersStatus.Properties.DataSource = _orderStatusPresenter.GetListOrderStatus();
            resLookUpStatus.DataSource = _orderStatusPresenter.GetListOrderStatus();
        }

        void LoadOrdersList()
        {
            gcOrdersList.DataSource = _ordersList = _ordersPresenter.GetByKey(txtSearchDate.EditValue, lookUpSearchCus.EditValue + string.Empty);
            gvOrdersList.BestFitColumns();
        }

        #endregion


        #region Method

        private bool Validation()
        {
            //kiem tra vi tri trong con trong' khong
            dxErrorProvider1.ClearErrors();

            if (lookUpOrdersStatus.EditValue == null || lookUpOrdersStatus.EditValue == "")
            {
                dxErrorProvider1.SetError(lookUpOrdersStatus, "Vui lòng nhập");
                return false;
            }
            else if (lookUpOrderCus.EditValue == null || lookUpOrderCus.EditValue == "")
            {
                dxErrorProvider1.SetError(lookUpOrderCus, "Vui lòng nhập");
                return false;
            }
            else if (txtOrderCusName.EditValue == null || txtOrderCusName.EditValue == "")
            {
                dxErrorProvider1.SetError(txtOrderCusName, "Vui lòng nhập");
                return false;
            }
            else if (txtOrderCusPhone.EditValue == null || txtOrderCusPhone.EditValue == "")
            {
                dxErrorProvider1.SetError(txtOrderCusPhone, "Vui lòng nhập");
                return false;
            }

            if (_order.orders_details.Count == 0)
            {
                ClsMsgBox.ThongTin("Vui lòng nhập sản phẩm");
                return false;
            }
            if ((int)lookUpOrdersStatus.EditValue == (int)OrdersStatus.Paid)
            {
                if (!isOutOfStock)
                {
                    if (txtCash.EditValue == null || txtCash.EditValue.ToString() == "0")
                    {
                        dxErrorProvider1.SetError(txtCash, "Vui lòng nhập");
                        return false;
                    }
                }
            }
            if ((int)lookUpOrdersStatus.EditValue == (int)OrdersStatus.Deposit)
            {
                if (txtDeposit.EditValue == null || txtDeposit.EditValue.ToString() == "0")
                {
                    dxErrorProvider1.SetError(txtDeposit, "Vui lòng nhập");
                    return false;
                }
            }
            //kiểm tra có lớn số lượng sp co lon hon trong kho khong
            foreach (var ordersDetailse in _order.orders_details)
            {
                var abc = _inventoryPresenter.GetByProductDetailsId(ordersDetailse.Ords_PRODUCT_DETAILS_ID)
                       .Sum(p => p.Inv_Quantity);
                if (_inventoryPresenter.GetByProductDetailsId(ordersDetailse.Ords_PRODUCT_DETAILS_ID).Sum(p => p.Inv_Quantity) < ordersDetailse.Ords_Quantity)
                {
                    isOutOfStock = true;
                    if (ClsMsgBox.XacNhan("Sản phẩm \"" + ordersDetailse.Ords_Product_Name
                                          +
                                          "\" không đủ số lượng trong kho.\nHóa đơn sẽ chuyển sang trạng thái đặt hàng tạm hết."))
                    {
                        lookUpOrdersStatus.EditValue = (int)OrdersStatus.OrderOutOfStock;
                        return true;
                    }
                    return false;
                }
            }

            return true;
        }

        private void ResetForm()
        {
            _order = null;
            txtOrderCode.EditValue = null;
            lookUpOrdersStatus.EditValue = null;
            txtOrderDate.EditValue = null;
            txtOrderUser.EditValue = null;
            txtOrdersDesc.EditValue = null;
            lookUpOrderCus.EditValue = null;
            txtSummary.EditValue = 0;
            spinDiscount.EditValue = 0;
            txtDeposit.EditValue = 0;
            txtCash.EditValue = 0;
            txtCharge.EditValue = 0;
        }



        #endregion


        /// ######################################################################################



        #region Property



        #endregion


        #region Enum

        private FromCode _fromCode = FromCode.FrmManagerOrder;

        #endregion














































    }
}